package com.example.botdemo02.gpt;

import com.alibaba.fastjson.JSON;
import com.example.botdemo02.enity.Image.Image;
import com.example.botdemo02.enity.Image.ImageGptMessage;
import com.example.botdemo02.enity.Image.ImageGptResponseParameter;
import com.example.botdemo02.enity.chat.ChatGptMessage;
import com.example.botdemo02.enity.chat.ChatGptRequestParameter;
import com.example.botdemo02.enity.chat.ChatGptResponseParameter;
import com.example.botdemo02.enity.chat.Choices;
import com.example.botdemo02.common_enum.FilePathEnum;
import com.example.botdemo02.strategy.context.UploadStrategyContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;


@Component
@Slf4j
public class GptUtils {
    /**
     * 自己chatGpt的ApiKey
     */
    @Value("${gpt.key}")
    private String apiKey;
    /**
     * chat对应的请求接口
     */
    @Value("${gpt.chaturl}")
    private String chatUrl;
    /**
     * 响应超时时间，毫秒
     */
    @Value("${gpt.timeout}")
    private int responseTimeout;
    /**
     * 默认编码
     */
    @Value("${gpt.charset}")
    private String charset;
    /**
     * gpt模式
     */
    @Value("${gpt.model}")
    private String model;
    /**
     * role
     */
    @Value("${gpt.role}")
    private String role;
    /**
     * image对应接口
     */
    @Value("${gpt.imageurl}")
    private String imageGPTUrl;

    /**
     * image的大小
     */
    @Value("${gpt.imagesize}")
    private String size;
    /**
     * 返回图片张数
     */
    @Value("${gpt.imagenum}")
    private Integer num;

    @Resource
    UploadStrategyContext uploadStrategyContext;
    /**
     * 创建一个ChatGptRequestParameter，用于携带请求参数
     */
    private static ChatGptRequestParameter chatGptRequestParameter = new ChatGptRequestParameter();

    public String getAnswer(CloseableHttpClient client, String question) {
        // 创建一个HttpPost
        HttpPost httpPost = new HttpPost(chatUrl);

        // 设置请求参数
        chatGptRequestParameter.addMessages(new ChatGptMessage(role, question));
        chatGptRequestParameter.setModel(model);
        HttpEntity httpEntity = null;
        try {
            // 对象转换为json字符串
            httpEntity = new StringEntity(JSON.toJSONString(chatGptRequestParameter), charset);
        } catch (Exception e) {
            log.info(question + "->json转换异常");
            return null;
        }
        httpPost.setEntity(httpEntity);
        // 设置请求头
        httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        // 设置登录凭证
        httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey);

        // 用于设置超时时间
        RequestConfig config = RequestConfig
                .custom()
                .setConnectTimeout(responseTimeout)
                .build();
        httpPost.setConfig(config);
//        接收返回值
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        try {
            response = client.execute(httpPost);
            entity = response.getEntity();
//            反序列化
            String responseMes = EntityUtils.toString(entity);
//            转为对象
            ChatGptResponseParameter responseParameter = JSON.parseObject(responseMes, ChatGptResponseParameter.class);
            // 遍历所有的Choices（一般都只有一个）
            String ans = "";
            for (Choices choice : responseParameter.getChoices()) {
                log.info("size:" + responseParameter.getChoices().size());
                ChatGptMessage message = choice.getMessage();
                chatGptRequestParameter.addMessages(new ChatGptMessage(message.getRole(), message.getContent()));
                String s = message.getContent().replaceAll("\n+", "\n");
                ans += s;
            }
            return ans;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
//        发生异常重置会话
        chatGptRequestParameter = new ChatGptRequestParameter();
        ;
        return "您当前的网络无法访问,会话已重置";
    }

    public String getImageURl(CloseableHttpClient client, String describe) {
        HttpPost httpPost = new HttpPost(imageGPTUrl);
        ImageGptMessage imageGptMessage = new ImageGptMessage(describe, size, num);
        String jsonString = JSON.toJSONString(imageGptMessage);
        HttpEntity httpEntity = new StringEntity(jsonString,charset);
        //        设置请求参数
        httpPost.setEntity(httpEntity);
        // 设置请求头
        httpPost.setHeader(org.apache.http.HttpHeaders.CONTENT_TYPE, "application/json");
        // 设置登录凭证
        httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey);
        //        设置请求超时时间
        RequestConfig timeOut = RequestConfig.custom().setConnectTimeout(responseTimeout).build();
        httpPost.setConfig(timeOut);
        //        发送请求
        CloseableHttpResponse response = null;
        InputStream stream = null;
        try{
            response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
//            反序列化
            String responseMes = EntityUtils.toString(entity);
//            转为对象
            ImageGptResponseParameter responseParameter = JSON.parseObject(responseMes, ImageGptResponseParameter.class);
            // 遍历所有的image（一般都只有一个）
            for (Image image : responseParameter.getData()) {
                HttpGet httpGet = new HttpGet(image.getUrl());
                response = client.execute(httpGet);
                HttpEntity en = response.getEntity();
                stream= en.getContent();
                String fileName = UUID.randomUUID()+".png";
                String lastUrl = uploadStrategyContext.executeUploadStrategy(fileName, stream, FilePathEnum.GPTIMG.getPath());
                String url = "[CQ:image,file="+lastUrl+"]";
//                String url = "[CQ:image,file=https://leyasuzhou-blog.oss-cn-beijing.aliyuncs.com/img/test.png]";
//                String url = image.getUrl();
                System.out.println(url);
                return url;
            }
        }catch (Exception e){
           log.info("图片生成出错了");
        }finally {
            try {
                stream.close();
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
